/*
 * @Author: liutongchao 1923236391@qq.com
 * @Date: 2023-05-29 11:54:12
 * @LastEditors: liutongchao 1923236391@qq.com
 * @LastEditTime: 2023-06-25 16:17:32
 * @FilePath: \greenbeeadmin\controllers\greenbee\upload.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package controllers

import (
	greenbeeUtils "greenbeeadmin/controllers/greenbee/utils"
	"math/rand"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

// 文件上传 controller
type CmfUploadFileController struct {
	MainBaseController
}

// 文件上传页面
func (c *CmfUploadFileController) Get() {
	id := c.GetString("id", "")
	types := c.GetString("types", "")
	if id == "" {
		c.Ctx.ResponseWriter.WriteHeader(200)
		return
	}
	js_prefix := "min" // 默认 多文件上传
	if types == "once" {
		//单文件上传
		js_prefix = "once"
	}

	c.Data["id_name"] = id
	c.Data["types"] = types
	c.Data["js_prefix"] = js_prefix
	c.TplName = "common/upload.html"
}

// 文件上传方法
func (c *CmfUploadFileController) Post() {
	input_filename := "file"
	f, h, err := c.GetFile(input_filename)
	//fmt.Println(h)
	var data interface{}
	if err != nil {
		//log.Fatal("getfile err ", err)
		data = err
		c.ErrorJson(0, "上传失败！", 0, data)
	}

	defer f.Close()

	filenameWithSuffix := path.Base(h.Filename) //获取文件名带后缀
	fileSuffix := path.Ext(filenameWithSuffix)  //获取文件后缀
	//文件图片格式验证
	d := make(map[string]string, 5)
	settings, err := c.GetSystemSetingData()
	if err == nil && settings.FileTypes != "" {
		strArrayNew := strings.Split(settings.FileTypes, "|")
		if len(strArrayNew) > 0 {
			for k, v := range strArrayNew {
				d[strconv.Itoa(k)] = "." + v
			}
		}

	} else {
		d = map[string]string{"1": ".jpg", "2": ".jpeg", "3": ".png", "4": ".gif"}
	}

	verify := greenbeeUtils.InMap(fileSuffix, d)
	if verify == "" {
		c.ErrorJson(0, "上传失败-图片格式有误！", 0, data)
	}
	// 文件大小限制
	fileMaxSize := 2048 * 1000 //默认 2048k = 2M
	if err == nil && settings.FileMaxSize > 0 {
		fileMaxSize = settings.FileMaxSize * 1000
	}
	if int(h.Size) > fileMaxSize {
		fileMaxSizeToKb := fileMaxSize / 1000
		c.ErrorJson(0, "请上传小于 "+strconv.Itoa(fileMaxSizeToKb)+"K 的文件", 0, data)
	}

	timestamp := time.Now().Unix()
	timestamps := strconv.FormatInt(timestamp, 10)
	//格式化为字符串,tm为Time类型
	tm := time.Unix(timestamp, 0)
	today := tm.Format("20060102")
	base_url := "static/upload/" + today + "/"
	fileInfo, err := os.Stat(base_url)
	if os.IsNotExist(err) || fileInfo.Size() == 0 {
		//按照日期创建目录
		os.MkdirAll(base_url, os.ModePerm)
	}

	//md5加密
	rand_num := strconv.Itoa(rand.Intn(100))
	write_str := timestamps + "_" + rand_num
	f_name := greenbeeUtils.Md5(write_str)
	filename := f_name + fileSuffix

	err = c.SaveToFile(input_filename, base_url+filename) // 保存位置在 static/upload, 没有文件夹要先创建
	if err == nil {
		datas := make(map[string]interface{})
		datas["filename"] = "/" + base_url + filename
		c.SuccessJson(200, datas, len(datas))
	}
	c.ErrorJson(0, "上传失败", 0, data)
}
